package com.liu.juc.sync;

/**
 * @author LIU
 * @version 1.0
 * @description TODO
 * @date 2024/2/20 10:34
 * 线程间通信
 * 虚假唤醒问题，wait哪里睡着，哪里醒。
 *        while (number != 0) 解决
 */
public class ThreadMessage {
    public static void main(String[] args) {
        Share share = new Share();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {

                try {
                    share.incr(); // +1
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {

                try {
                    share.incr(); // +1
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.decr(); // -1
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "CC").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    share.decr(); // -1
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "DD").start();

    }


}

// 资源类
class Share {
    // 共享
    private int number = 0;

    // +1 方法
    public synchronized void incr() throws InterruptedException {
        // 判断
        while (number != 0) {
            this.wait();
        }

        // 干活
        System.out.println(Thread.currentThread().getName() + " :: " + number++);

        // 通知其他线程
        this.notifyAll();
    }

    // -1 方法
    public synchronized void decr() throws InterruptedException {
        // 判断
        while (number != 1) {
            this.wait();
        }

        // 干活
        System.out.println(Thread.currentThread().getName() + " :: " + number--);

        // 通知其他线程
        this.notifyAll();
    }
}
